package com.example.librarymanagement.controller;

import com.example.librarymanagement.exception.BizException;
import com.example.librarymanagement.result.ResultCode;
import com.example.librarymanagement.util.Const;
import com.example.librarymanagement.util.RedisUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author fgba
 */
@Slf4j
@RestController
public class AuthController {

    @Resource
    private Producer producer;

    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/captcha")
    public Map<String, String> getCaptcha() {

        Map<String, String> map = new HashMap<>();
        String code = producer.createText();
        String key = UUID.randomUUID().toString();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            throw new BizException(ResultCode.SYSTEM_RESOURCE_ERROR);
        }
        BASE64Encoder encoder = new BASE64Encoder();

        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        map.put("token", key);
        map.put("captchaImg", base64Img);

        return map;
    }
}
